package com.ling.tools.login.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonEncoding;
import com.google.gson.JsonObject;
import com.ling.tools.login.entity.TpParam;
import com.ling.tools.login.entity.User;
import com.ling.tools.login.service.UserService;
import com.ling.tools.login.utils.Result;
import com.ling.tools.login.utils.ResultCode;
import jdk.nashorn.internal.parser.JSONParser;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;



@RestController
@RequestMapping("user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * @return
     * @author Ling
     * @Param
     * @Date 2020/2/28 11:18
     * @Description 用户注册
     */
    @PostMapping("/register")
    public Result register(@RequestBody User user) {
        Result result = new Result();
        if (null == user) {
            result.setResultCode(ResultCode.USER_USERINFO_NOT_BLANK);
        }
        result = userService.saveUser(user);
        return result;
    }

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        Result result = new Result();
        if(null == user){
            result.setResultCode(ResultCode.USER_USERINFO_NOT_BLANK);
        }
        executeLogin(user,result);
        return result;
    }


    private void executeLogin(User user,Result r) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(),user.getPassword());

        try {
            subject.login(token);
            r.setResultCode(ResultCode.SUCCESS);
        }catch (UnknownAccountException e){
            r.setResultCode(ResultCode.USER_DOSENOT_EXISTS);
        }catch (Exception e){
            r.setResultCode(ResultCode.FAIL);
        }

    }











}
